﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Xml;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;

using System.Web.Script.Serialization;    //导入解析Json的类 
/// <summary>
///TextMessage 的摘要说明
/// </summary>
/// 
namespace WeiXin
{

    public class TextMsgManage : MsgManage
    {
        public class ParcelInfo
        {
            public String boxId;
            public String courierCorp;
            public String courierId;
            public String getTime;
            public String packageId;
            public String packageStatus;
            public String parcelId;
            public String storeTime;
            public String terminalId;
            public String userPhone;
        }
        static CookieContainer myCookieContainer = null;
        public TextMsgManage(String msg)
        {
            try
            {
                var xDoc = XDocument.Parse(msg);
                var q = (from c in xDoc.Elements() select c).ToList();
                var msgType = q.Elements("MsgType").First().Value; // 获取信息内容的类型

                var _tmpContent = "";    //最终回复
                int count_Response = 0;  //自动回复数量
                String default_response_message = "";  //无法识别的指令的默认回复语句

                if (0 == string.Compare("text", msgType, true))   //再次验证是text消息
                {
                    //接到的xml
                    var model = new
                    {
                        ToUserName = q.Elements("ToUserName").First().Value,
                        FromUserName = q.Elements("FromUserName").First().Value,
                        CreateTime = q.Elements("CreateTime").First().Value,
                        MsgType = q.Elements("MsgType").First().Value,
                        Content = ("" + q.Elements("Content").First().Value).Trim(),
                        MsgId = q.Elements("MsgId").First().Value
                    };

                    Log.WriteLog(DefaultData.ACTION_TYPE_TEXTMSG_REC + msg);


                    if (false == string.IsNullOrWhiteSpace(model.Content))//如果内容不为空
                    {
                        XDocument xml = XDocument.Load(HttpContext.Current.Server.MapPath(DefaultData.PATH_XML_TEXTMSGMANAGE));
                        XElement xeRoot = xml.Root;
                        IEnumerable<XElement> etors = xeRoot.Elements("Msg");


                        foreach (XElement itemMsg in etors)
                        {
                            //获取无法识别的指令的默认回复语句
                            if (itemMsg.Element("Key").Value == "default_response_message")
                            {
                                default_response_message = itemMsg.Element("Content").Value;
                            }
                            //如果请求语句在xml匹配
                            if (itemMsg.Element("Key").Value == model.Content.ToLower())
                            {
                                _tmpContent = itemMsg.Element("Content").Value;
                                if (false == string.IsNullOrWhiteSpace(_tmpContent))
                                {
                                    var textTpl = "<xml>"
                                                  + "<ToUserName><![CDATA[{0}]]></ToUserName>"
                                                  + "<FromUserName><![CDATA[{1}]]></FromUserName>"
                                                  + "<CreateTime>{2}</CreateTime>"
                                                  + "<MsgType><![CDATA[{3}]]></MsgType>"
                                                  + "<Content><![CDATA[{4}]]></Content>"
                                                  + "<FuncFlag>{5}</FuncFlag>"
                                                  + "</xml>";

                                    //回复对应xml中的语句
                                    System.Web.HttpContext.Current.Response.Write(string.Format(textTpl, model.FromUserName, model.ToUserName, ConvertDateTimeInt(DateTime.Now), "text", _tmpContent, 0));

                                    Log.WriteLog(DefaultData.ACTION_TYPE_TEXTMSG_RESPONSE + string.Format(textTpl, model.FromUserName, model.ToUserName, ConvertDateTimeInt(DateTime.Now), "text", _tmpContent, 0));

                                    count_Response++;   //如果xml中有多条匹配的语句，连续回复，并计数

                                }
                            }
                        }

                        if (count_Response == 0)   //没有找到对应回复办法 ， 回复默认消息
                        {
                            _tmpContent = default_response_message;
                            if (false == string.IsNullOrWhiteSpace(_tmpContent))
                            {
                                var textTpl = "<xml>"
                                              + "<ToUserName><![CDATA[{0}]]></ToUserName>"
                                              + "<FromUserName><![CDATA[{1}]]></FromUserName>"
                                              + "<CreateTime>{2}</CreateTime>"
                                              + "<MsgType><![CDATA[{3}]]></MsgType>"
                                              + "<Content><![CDATA[{4}]]></Content>"
                                              + "<FuncFlag>{5}</FuncFlag>"
                                              + "</xml>";



                                string webserviceUrl = "http://service.24box.cn:21198/YouBoxAdmin/login?username=admin&password=admin&returnType=json";
                                string charSet = "utf-8";
                                string pageContent = "";
                                string contentlist = "";
                                try
                                {
                                    pageContent = GetWebServiceContent(webserviceUrl, charSet);
                                    Console.WriteLine(pageContent);

                                    if (model.Content.Length == 11)
                                    {
                                        webserviceUrl = "http://service.24box.cn:21198/YouBoxAdmin/packageDetail?phoneNum=" + model.Content + "&returnType=json";
                                    }
                                    else
                                    {
                                        webserviceUrl = "http://service.24box.cn:21198/YouBoxAdmin/packageDetailByParcelID?parcelID=" + model.Content + "&returnType=json";
                                    }
                                    pageContent = GetWebServiceContent(webserviceUrl, charSet);

                                    // 无数据
                                    if (pageContent.Equals("[]"))
                                    {
                                        pageContent = "无数据或错误指令,请直接输入正确号码(11位判断手机号，其他判断为快件号)查询";
                                    }

                                    else
                                    {
                                        //                                        string te = @"[{'boxId':2,'courierCorp':'快递员','courierId':16,
                                        //'getTime':'2013-06-03T16:59:28','packageId':2326,
                                        //'packageStatus':1,'parcelId':'1900420032323',
                                        //'storeTime':'2013-06-03T16:33:28','terminalId':3,
                                        //'userPhone':13696837370},{'boxId':2,'courierCorp':'快递员','courierId':16,
                                        //'getTime':'2013-06-03T16:59:28','packageId':2326,
                                        //'packageStatus':1,'parcelId':'1900420032323',
                                        //'storeTime':'2013-06-03T16:33:28','terminalId':3,
                                        //'userPhone':13696837370},{'boxId':2,'courierCorp':'快递员','courierId':16,
                                        //'getTime':'2013-06-03T16:59:28','packageId':2326,
                                        //'packageStatus':1,'parcelId':'1900420032323',
                                        //'storeTime':'2013-06-03T16:33:28','terminalId':3,
                                        //'userPhone':13696837370}]";

                                        //                                        pageContent = te;
                                        pageContent = pageContent.Replace("\"", "'");
                                        pageContent = "{'info':" + pageContent + "}";
                                        JavaScriptSerializer serializer = new JavaScriptSerializer();
                                        Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(pageContent);
                                        object[] info = (object[])json["info"];
                                        Dictionary<string, object> val;

                                        List<ParcelInfo> listparcelinfo = new List<ParcelInfo>();

                                        for (int i = 0; i < info.Length; i++)
                                        {

                                            val = (Dictionary<string, object>)info[i];
                                            ParcelInfo parcelinfo = new ParcelInfo();
                                            foreach (KeyValuePair<string, object> str in val)
                                            {

                                                if (str.Key.Equals("boxId"))
                                                {
                                                    if (str.Value == null)
                                                        parcelinfo.boxId = "null";
                                                    else
                                                        parcelinfo.boxId = str.Value.ToString();
                                                }
                                                else if (str.Key.Equals("courierCorp"))
                                                {
                                                    if (str.Value == null)
                                                        parcelinfo.courierCorp = "null";
                                                    else
                                                        parcelinfo.courierCorp = str.Value.ToString();
                                                }
                                                else if (str.Key.Equals("courierId"))
                                                {
                                                    if (str.Value == null)
                                                        parcelinfo.courierId = "null";
                                                    else
                                                        parcelinfo.courierId = str.Value.ToString();
                                                }
                                                else if (str.Key.Equals("getTime"))
                                                {
                                                    if (str.Value == null)
                                                        parcelinfo.getTime = "null";
                                                    else
                                                        parcelinfo.getTime = str.Value.ToString();
                                                }
                                                else if (str.Key.Equals("packageId"))
                                                {
                                                    if (str.Value == null)
                                                        parcelinfo.packageId = "null";
                                                    else
                                                        parcelinfo.packageId = str.Value.ToString();
                                                }
                                                else if (str.Key.Equals("packageStatus"))
                                                {
                                                    if (str.Value == null)
                                                        parcelinfo.packageStatus = "null";
                                                    else
                                                        parcelinfo.packageStatus = str.Value.ToString();
                                                }
                                                else if (str.Key.Equals("parcelId"))
                                                {
                                                    if (str.Value == null)
                                                        parcelinfo.parcelId = "null";
                                                    else
                                                        parcelinfo.parcelId = str.Value.ToString();
                                                }
                                                else if (str.Key.Equals("storeTime"))
                                                {
                                                    if (str.Value == null)
                                                        parcelinfo.storeTime = "null";
                                                    else
                                                        parcelinfo.storeTime = str.Value.ToString();
                                                }
                                                else if (str.Key.Equals("terminalId"))
                                                {
                                                    if (str.Value == null)
                                                        parcelinfo.terminalId = "null";
                                                    else
                                                        parcelinfo.terminalId = str.Value.ToString();
                                                }
                                                else if (str.Key.Equals("userPhone"))
                                                {
                                                    if (str.Value == null)
                                                        parcelinfo.userPhone = "null";
                                                    else
                                                        parcelinfo.userPhone = str.Value.ToString();
                                                }

                                            }
                                            listparcelinfo.Add(parcelinfo);
                                        }
pageContent  ="";
                                        for (int i = 0; i < listparcelinfo.Count; i++)
                                        {
                                            //contentlist = "";
                                            //contentlist = contentlist + "第" + (i + 1) + "条快件信息\r\n";
                                            //contentlist = contentlist + "柜号ID:" + listparcelinfo[i].boxId + "\r\n";
                                            //contentlist = contentlist + "终端ID:" + listparcelinfo[i].terminalId + "\r\n";
                                            //contentlist = contentlist + "快件ID:" + listparcelinfo[i].parcelId + "\r\n";
                                            //contentlist = contentlist + "快件状态:" + listparcelinfo[i].packageStatus + "\r\n";
                                            //contentlist = contentlist + "邮员ID:" + listparcelinfo[i].courierId + "\r\n";
                                            //contentlist = contentlist + "隶属公司:" + listparcelinfo[i].courierCorp + "\r\n";
                                            //contentlist = contentlist + "联系电话:" + listparcelinfo[i].userPhone + "\r\n";
                                            //contentlist = contentlist + "取件时间:\r\n" + listparcelinfo[i].getTime + "\r\n";
                                            //contentlist = contentlist + "存件时间:\r\n" + listparcelinfo[i].storeTime + "\r\n";
                                            //contentlist = contentlist + "\r\n\r\n";

                                            pageContent = pageContent + "第" + (i + 1) + "条快件信息\r\n";
                                            pageContent = pageContent + "柜号:" + listparcelinfo[i].boxId + "\r\n";
                                            pageContent = pageContent + "隶属公司:" + listparcelinfo[i].courierCorp + "\r\n";
                                            pageContent = pageContent + "邮员ID:" + listparcelinfo[i].courierId + "\r\n";
                                            pageContent = pageContent + "取件时间:" + listparcelinfo[i].getTime + "\r\n";
                                            pageContent = pageContent + "快件ID:" + listparcelinfo[i].parcelId + "\r\n";
                                            pageContent = pageContent + "快件状态:" + listparcelinfo[i].packageStatus + "\r\n";
                                            pageContent = pageContent + "存件时间:" + listparcelinfo[i].storeTime + "\r\n";
                                            pageContent = pageContent + "终端ID:" + listparcelinfo[i].terminalId + "\r\n";
                                            pageContent = pageContent + "联系电话:" + listparcelinfo[i].userPhone + "\r\n";
                                            pageContent = pageContent + "\r\n";

                                            //System.Web.HttpContext.Current.Response.Write(string.Format(textTpl, model.FromUserName, model.ToUserName, ConvertDateTimeInt(DateTime.Now), "text", contentlist, 0));

                                            //Log.WriteLog(DefaultData.ACTION_TYPE_TEXTMSG_RESPONSE + string.Format(textTpl, model.FromUserName, model.ToUserName, ConvertDateTimeInt(DateTime.Now), "text", contentlist, 0));

                                        }
                                    }



                                    Console.WriteLine(pageContent);

                                }
                                catch (Exception err)
                                {
                                    Console.WriteLine(err.ToString());
                                }

                                //if (contentlist.Equals(""))
                                //{
                                    System.Web.HttpContext.Current.Response.Write(string.Format(textTpl, model.FromUserName, model.ToUserName, ConvertDateTimeInt(DateTime.Now), "text", pageContent, 0));

                                    Log.WriteLog(DefaultData.ACTION_TYPE_TEXTMSG_RESPONSE + string.Format(textTpl, model.FromUserName, model.ToUserName, ConvertDateTimeInt(DateTime.Now), "text", pageContent, 0));
                                //}

                                
                                count_Response++;
                            }
                        }

                        Log.WriteLog("**********************************************************\r\n\r\n");

                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog("错误位于TextManage : 回复处理异常" + ex.ToString());
            }
            System.Web.HttpContext.Current.Response.End();
        }

        /// <summary>
        /// datetime转换为unixtime
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        private int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        /// <summary>
        /// 请求WebService
        /// </summary>
        /// <param name="webserviceUrl"></param>
        /// <param name="charset"></param>
        /// <returns></returns>
        static string GetWebServiceContent(string webserviceUrl, string charset)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webserviceUrl);
            request.Method = "GET";
            request.Timeout = 60000;

            if (myCookieContainer == null)
                myCookieContainer = new CookieContainer();

            request.CookieContainer = myCookieContainer;


            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            response.Cookies = myCookieContainer.GetCookies(request.RequestUri);


            Stream streamReceive = response.GetResponseStream();
            Encoding encoding = Encoding.Default;
            if (!string.IsNullOrEmpty(charset) && Encoding.GetEncoding(charset) != Encoding.Default)
            {
                encoding = Encoding.GetEncoding(charset);
            }

            StreamReader streamReader = new StreamReader(streamReceive, encoding);
            return streamReader.ReadToEnd();
        }
    }
}